
<!--
	作者：lsd
	时间：2020-4-16
	描述：自动派单规则设置
-->
<template>
	<div class="m-view-autoSendLeafletRule m-window">
		<!-- 左边树结构 -->
		<div class="m-leftTree">
			<el-select 
				v-model="formSearch.plantCode" 
				filterable 
				@change="changeCompany"
				:filter-method="filterFactory"
				placeholder="请选择工厂" 
				v-loading="loadingDia">
				<el-option
					v-for="item in optionsFactory"
					:key="item.plantCode"
					:label="item.plantName"
					:value="item.plantCode">
					<span style="float: left">{{ item.plantName }}</span>
					<span style="float: right; color: #8492a6; font-size: 13px">{{ item.plantCode }}</span>
				</el-option>
			</el-select>
      <div class="m-agTable">
				<ag-grid-components
					ref="agGridComponentPurchaser"
					:getGridOptions="gridOptionsPurchaser"
					:getColumnDefs="columnDefsPurchaser"
					rowSelection="single"
					v-loading="loading"
					:isColFit="true">
				</ag-grid-components>
			</div>
    </div>

		<!-- 右边列表 -->
		<div class="m-rightContent">
			<!-- 搜索头 -->
			<div class="m-condition">
				<el-row :gutter="5">
					<el-form
						:model="formSearch"
						ref="formSearch"
						label-width="70px"
						:inline-message="true"
						label-position="left"
					>
						<el-col :span="6">
							<el-form-item label="物料组" class="rightItem">
								<el-input
									value-key="id"
									v-model.trim="formSearch.matgroupNo"
									placeholder="请输入编码或描述"
									clearable
									maxlength="20"
								></el-input>
							</el-form-item>
						</el-col>
					</el-form>

					<el-col :span="2" :offset="2">
						<el-button type="primary" @click="pageClick(true)">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="addPurchaserMaterials()" v-show="tabActiveName == 'allList'">保存</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="deleteAutoRule"  v-show="tabActiveName == 'selectList'"> 删除</el-button>
					</el-col>
				</el-row>
			</div>

			<!-- 表单 -->
			<el-tabs type="card" v-model="tabActiveName" @tab-click="handleClick">
				<el-tab-pane label="已选列表" name="selectList">
					<div class="m-agTable m-bottom" v-loading="loading">
						<agGridComponents
							ref="agGridComponent"
							:getGridOptions="gridOptions"
							:getColumnDefs="columnDefsSelected"
							:getRowSelection="'multiple'"
							:isColFit="true"
						></agGridComponents>
					</div>
					<!-- 页脚 -->
					<div class="m-page">
						<el-pagination
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
							:current-page="pageInfo.currentPage"
							:page-sizes="[50,100,200,500]"
							:page-size="pageInfo.pageSize"
							layout="total, sizes, prev, pager, next, jumper"
							:total="total"
						></el-pagination>
					</div>
				</el-tab-pane>
        <el-tab-pane label="未选列表" name="allList">
					<div class="m-agTable m-bottom" v-loading="loading">
						<agGridComponents
							ref="agGridComponentAllList"
							:getGridOptions="gridOptions"
							:getColumnDefs="columnDefs"
							:getRowSelection="'multiple'"
							:isColFit="true"
						></agGridComponents>
					</div>
					<!-- 页脚 -->
					<div class="m-page">
						<el-pagination
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
							:current-page="pageInfoAllList.currentPage"
							:page-sizes="[50,100,200,500]"
							:page-size="pageInfoAllList.pageSize"
							layout="total, sizes, prev, pager, next, jumper"
							:total="totalAllList"
						></el-pagination>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>

		<!-- 物料派单员弹框 -->
		<dialogSrmMaterialsPurchaser
			:dialogVisible="diaMaterials"
			:plantCode="diaMaterialsData.plantCode"
			:plantName="diaMaterialsData.plantName"
			:matgroupCode="diaMaterialsData.matgroupCode"
			:matgroupName="diaMaterialsData.matgroupName"
			:isAutoRule="true"
			@dialogClose="closeDia">
		</dialogSrmMaterialsPurchaser>
  </div>
</template>
  
<script>
import agGridComponents from "@/components/agGridComponents.js";
import dialogSrmMaterialsPurchaser from "./common/dialogSrmMaterialsPurchaser"
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import Vue from 'vue';

const btnLink = Vue.extend({
	template: `<span> <el-button type="text" @click="details" class="rendererClass" size="mini">{{params.value}}</el-button> </span>`,
  methods: {
    details () {	
			this.params.context.componentParent.diaMaterials = true;
			this.params.context.componentParent.diaMaterialsData.matgroupCode = this.params.value;
			this.params.context.componentParent.diaMaterialsData.matgroupName = this.params.data.matgroupName;
			let plantInfo = this.params.context.componentParent.optionsTempFactory.filter(item => item.plantCode==this.params.context.componentParent.formSearch.plantCode);
			this.params.context.componentParent.diaMaterialsData.plantCode = plantInfo[0].plantCode;
			this.params.context.componentParent.diaMaterialsData.plantName = plantInfo[0].plantName;
		},
  }
});

/**
 * autoSendLeafletRule
 * 自动派单规则设置
 */
export default {
	name: 'autoSendLeafletRule',
	components:{
		agGridComponents, dialogSrmMaterialsPurchaser
	},
	data(){
		return {
			formSearch:{//查询表
				matgroupNo: '',
				sapNum: '',
				plantCode: ''
			},
			formPurchaserMaterials:{ //新增&编辑采购员表
				sapNum: '',
				matgroupCode: '',
				cond: '',
				plantCode: ''
			},
			optionsFactory:[],//工厂列表
			optionsTempFactory: [], //工具人，专门用来过滤的
			//表格参数
			gridOptions: '',
			columnDefs: [],
			gridOptionsPurchaser: '',//采购员表
			columnDefsPurchaser: [],
			rowDataPurchaser: [],//采购员列表
			rowDataMaterials: [], //全部物料
			rowData: [], // 已选列表数据
			rowDataAllSelected: [],//已选的全部数据
			rowLog: [],//记录删除的数据
			//tab参数
			tabActiveName: 'selectList',
			//页脚参数
			pageInfo: { //已选列表
				pageSize: 100,
				currentPage: 1,
			},
			total: 0,
			pageInfoAllList: { //全部列表
				pageSize: 100,
				currentPage: 1,
			},
			totalAllList: 0,
			//加载参数
			loading: false,//页面的
			loadingDia: false,//弹框的

			//物料派单员自动规则弹框参数
			diaMaterials: false,
			diaMaterialsData:{
				plantCode: '',
				plantName: '',
				matgroupCode: '',
				matgroupName: ''
			}
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,//单元格选中,false为选中整行
		};
		this.columnDefs = [
			{	headerName: "物料组", field: "matgroupNo", width: 200, checkboxSelection: true, headerCheckboxSelection: true, cellRendererFramework: btnLink	},
			{ headerName: "物料组描述", field: "matgroupName", width: 200 },
		];
		this.columnDefsSelected = [
			{	headerName: "物料组", field: "matgroupCode", width: 200, checkboxSelection: true, headerCheckboxSelection: true, cellRendererFramework: btnLink	},
			{ headerName: "物料组描述", field: "matgroupName", width: 200 },
		];
		//采购员表
    this.gridOptionsPurchaser = {
	 		context: {
	 			componentParent: this
	 		},
      enableColResize: true,
      rowSelection: "single",
	 		localeText: localeText,
			suppressRowClickSelection: false,//单元格选中,false为选中整行
			onRowClicked: ( event ) =>{
				this.formSearch.sapNum = event.data.sapNum;
				this.getSelectedList(true);
				this.getAllList(true);
			}
    };
    this.columnDefsPurchaser = [
      { headerName: "采购员", field: "purcheaserName", checkboxSelection: true}
    ];

	},
	mounted(){
		this.getAllList();
		this.getFactoryList();
	},
	methods:{
		/**
		 * @vuese
		 * 获取未选列表方法
		 * 
		 * @arg 参数是布尔值， true就是点击触发，false就是非点击触发
		 */
		getAllList(isClick){
			this.pageInfoAllList.currentPage = isClick ? 1 : this.pageInfoAllList.currentPage;
			let param = {
				...this.formSearch,
				...this.pageInfoAllList,
			};
			if(param.sapNum == "") return
			this.loading = true;
			_Api
				.getNoSelectedAutoRuleList(param)
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.rowDataMaterials = res.data.rows;
						this.totalAllList = res.data.total;
						this.$refs.agGridComponentAllList.gridOptions.api.setRowData(res.data.rows);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 查询已选列表
		 * 
		 * @arg isClick:参数是布尔值， true就是点击触发，false就是非点击触发
		 */
		getSelectedList(isClick){
			this.loading = true;
			let row = this.$refs.agGridComponentPurchaser.gridOptions.api.getSelectedRows();
			this.pageInfo.currentPage = isClick ? 1 : this.pageInfo.currentPage;
			let param = {
				...this.formSearch,
				...this.pageInfo,
			};
			param.matgroupCode = param.matgroupNo
			param.sapNum = row.length == 0?null:param.sapNum;
			param.plantCode = row.length == 0?null:param.plantCode
			delete param.matgroupNo
			_Api
				.getAutoRuleList(param)
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.rowData = res.data.rows;
						this.total = res.data.total;
						this.$refs.agGridComponent.gridOptions.api.setRowData(res.data.rows);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		
		/**
		 * @vuese
		 * 新增自动派单规则方法
		 * 
		 */
		addPurchaserMaterials(){
			
			//条件检测
			if(this.formSearch.plantCode == ""){ //工厂不能为空
				this.$alert("请选择工厂", { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				return
			}
			if(this.formSearch.sapNum == ""){ //人不能为空
				this.$alert("请选择采购员", { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				return
			}
			//获取选中物料组
			let list = this.$refs.agGridComponentAllList.gridOptions.api.getSelectedRows();
			if( list.length <= 0){ //物料组不能为空
				this.$alert("请选择物料组", { showClose: false, confirmButton: "确定", customClass: "alertPrompt" });
				return
			}
			

			//填充参数
			let param = [];
			for(let i = 0; i < list.length; i++){
				let temp = {
					matgroupCode: list[i].matgroupNo==null?list[i].matgroupCode:list[i].matgroupNo,
					sapNum: this.formSearch.sapNum,
					cond: "等于",
					plantCode: this.formSearch.plantCode,
					creatorId: this.$global.user.id,
					creator: this.$global.user.employeeName//创建人
				}
				param.push(temp)
			}
			//发出请求
			this.$confirm('是否保存', "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				_Api
					.addAutoSendLeafleRule(param)
					.then(res => {
						this.loading = false;
						if (res.data.code == 1) {
							this.$message({ message: "保存成功", type: "success" });
							this.getSelectedList();//刷新已选列表
							this.getAllList();
						} else {
							this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						}
					})
					.catch(err => {
						this.loading = false;
						this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					});
			})
		},

		/**
		 * @vuese
		 * 删除自动派单规则方法
		 */
		deleteAutoRule(){
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if(row.length <= 0){
				this.$alert("提示：请至少选择一条数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"					
				});
				return
			}

			let param = {
				ids: row.map(v=>v.id),
			}
			this.$confirm('是否删除这些数据', "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				_Api
					.deleteAutoSendLeadfletRule(param)
					.then(res => {
						this.loading = false;
						if (res.data.code == 1) {
							this.$message({
								message: '删除成功！',
								type: "success"
							});
							this.getSelectedList();//刷新
						} else {
							this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						}
					})
					.catch(err => {
						this.loading = false;
						this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					});
			})
		},

		
		/**
		 * @vuese 
		 * 根据工厂获取全部采购员方法
		 */
		getPurcheaserList(){
      let plantCode = this.formSearch.plantCode
      if(plantCode == "" || plantCode == null){
        return 
      }
			this.loadingDia = true;
		  _Api
		  	.getAllPurchaserList({plantCode})
		  	.then(res => {
		  		this.loadingDia = false;
		  		if (res.data.code == 1) {
            this.rowDataPurchaser = res.data.rows;
						this.$refs.agGridComponentPurchaser.gridOptions.api.setRowData(res.data.rows);
						//清空参数
						this.rowDataAllSelected = [];
						this.formSearch.sapNum = "";
		  		} else {
		  			this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
		  		}
		  	})
		  	.catch(err => {
		  		this.loadingDia = false;
		  		this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
    },

		/**
		 * @vuese
		 * 获取工厂列表方法
		 */
		getFactoryList(){
			this.loadingDia = true;
			_Api
				.getFactoryList()
				.then(res => {
					this.loadingDia = false;
					if (res.data.code == 1) {
						this.optionsFactory = res.data.rows;
						this.optionsTempFactory = res.data.rows;
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loadingDia = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},


		/**
		 * @vuese
		 * 改变页脚总条数方法
		 * 
		 * @arg 参数是 int 值，代表一页有多少条数据
		 */
		handleSizeChange (val) {
			if( this.tabActiveName == 'allList' ){
				this.pageInfoAllList.currentPage = 1;
				this.pageInfoAllList.pageSize = val;
			}else{
				this.pageInfo.pageSize = val;
				this.pageInfo.currentPage = 1;
			}
			this.pageClick();
		},

		/**
		 * @vuese
		 * 切换公司方法
		 */
		changeCompany(){
			this.$refs.agGridComponentPurchaser.gridOptions.api.forEachNode(function(node) {
        node.setSelected(false);
			});
			this.$refs.agGridComponentPurchaser.gridOptions.api.setRowData([]);
			this.getAllList(true);
			this.getSelectedList(true);
			this.getPurcheaserList();	
		},

		/**
		 * @vuese
		 * 翻页方法
		 * 
		 * @arg 参数是 int 值，代表页数
		 */
		handleCurrentChange (val) {
			if( this.tabActiveName == 'allList' ){
				this.pageInfoAllList.currentPage = val;
			}else{
				this.pageInfo.currentPage = val;
			}
			this.pageClick();
		},
		
		/**
		 * @vuese
		 * tab 点击事件
		 */
		handleClick(tab){
			this.pageInfo.currentPage = 1;
			if( tab.name == 'allList' ){
				this.getAllList();
			}else{
				this.getSelectedList();
			}
		},

		/**
		 * @vuese
		 * 翻页查询方法
		 * 
		 * @arg isClick:是布尔值， true就是点击触发，false就是非点击触发
		 */
		pageClick(isClick){
			if( this.tabActiveName == 'allList' ){
				this.getAllList(isClick);
			}else{
				this.getSelectedList(isClick);
			}
		},
		/**
		 * @vuese
		 * 过滤工厂
		 * 
		 * @arg value:传入的是检索值, 用于过滤
		 */
		filterFactory (value) {
			if (value != '') {
				this.optionsFactory = this.optionsTempFactory.filter(item => item.plantCode.indexOf(value) > -1 || item.plantName.indexOf(value) > -1)
			} else {
				this.optionsFactory = this.optionsTempFactory
			}
		},

		/**
		 * @vuese
		 * 关闭选择物料弹窗
		 */
		closeDia(){
			this.diaMaterials = false;
			this.diaMaterialsData.matgroupCode = "";//很重要的，别删，在弹框那边是监听这个变化的
		},
	}
}
</script>

<style lang="less">
.m-view-autoSendLeafletRule{
	.m-leftTree{
		width: 290px;
		.m-agTable{
			position: absolute;
			left: 0;
			right: 0;
			top: 62px;
			bottom: 0;
		}
	}
	.m-rightContent{
		top: 0;
		left: 300px;
	}
	.el-tabs__nav-scroll{
		background-color: #fff;
		.is-active{
			color: #fff;
			background: #409eff;
		}
	}
	
	.el-tabs__content{
		top: 55px;
		left: 0;
		right: 0;
		bottom: 0;
	}
}
</style>
